import sys
import threading
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QMainWindow, QSplashScreen
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtGui import QPixmap
from dash_app import DashApp

class MainWindow(QMainWindow):
    """
    主窗口类，直接嵌入Dash应用程序
    """

    def __init__(self, dash_app):
        """
        初始化主窗口

        Args:
            dash_app (DashApp): Dash应用程序实例
        """
        super().__init__()

        self.dash_app = dash_app
        self.port = dash_app.port
        self.dash_url = f"http://localhost:{self.port}"

        self.setWindowTitle("数据可视化仪表盘")
        
        # 设置窗口最大化
        self.showMaximized()

        # 添加状态栏信息
        self.statusBar().showMessage("数据可视化仪表盘已就绪 - 版本1.0")

        # 创建WebEngineView来嵌入Dash应用
        self.web_view = QWebEngineView()
        self.setCentralWidget(self.web_view)
        
        # 加载Dash应用URL
        self.web_view.load(self.dash_url)

def run_dash(dash_app):
    """
    在单独的线程中运行Dash应用程序

    Args:
        dash_app (DashApp): Dash应用程序实例
    """
    dash_app.run(debug=False)

def main():
    """
    主函数
    """
    # 创建QApplication实例
    app = QApplication(sys.argv)

    # 创建启动画面
    splash_pix = QPixmap(400, 300)
    splash_pix.fill(Qt.white)
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.showMessage("正在加载数据可视化仪表盘...", Qt.AlignCenter | Qt.AlignBottom, Qt.black)
    splash.show()
    app.processEvents()

    # 创建Dash应用程序实例
    dash_app = DashApp(port=8050)

    # 在单独的线程中运行Dash服务器
    dash_thread = threading.Thread(target=run_dash, args=(dash_app,), daemon=True)
    dash_thread.start()

    # 创建主窗口
    window = MainWindow(dash_app)

    # 显示主窗口并关闭启动画面
    window.show()
    splash.finish(window)

    # 运行应用程序
    sys.exit(app.exec())

if __name__ == "__main__":
    main()
